
from sqlalchemy import and_
from app.core.exception import ApiException
from app.entity.projectMessage import ProjectMessage


class ProjectMessageService:
    toPage:dict={
        "invite":"/pages/aaProject/joinProject"
    }

    def hadInvitedMessage(projectId,invitee)->bool:
        toPageUrl=f"{ProjectMessageService.toPage['invite']}?pid={projectId}"
        cnt=ProjectMessage().query().where(and_(ProjectMessage.toPage==toPageUrl,
                                                ProjectMessage.receiver==invitee,
                                                ProjectMessage.reader==None)).count()
        return cnt>0

    def readAllMessage(userid):
        # 设置已读只设置系统的 即projectid=-1
        ProjectMessage().query().where(and_(ProjectMessage.receiver==userid,
                                            ProjectMessage.reader.not_like(f"%{userid}%"),
                                            ProjectMessage.projectId==-1)).\
                         update({ProjectMessage.reader:"f{ProjectMessage.reader},{userid}"})

    def readMessage(messageId,userid)->ProjectMessage:
        pm=ProjectMessageService.getMessageById(messageId)
        if pm.receiver!=userid:
            raise ApiException("无权读取此消息")
        if pm.reader==None:
            pm.reader=""
        readerList=pm.reader.split(",")
        if str(userid) not in readerList:
            readerList.append(str(userid))
        pm.reader=','.join(readerList)
        pm.save()
        return pm

    def getMessageById(messageId)->ProjectMessage:
        return ProjectMessage().query().filter(ProjectMessage.id==messageId).first()
    
    def listMyMessage(userid)->list:
        messageList:list[ProjectMessage]=ProjectMessage().query().\
            filter(ProjectMessage.receiver==userid).order_by(ProjectMessage.createdAt.desc()).all()
        resplist=[]
        for message in messageList:
            json=message.toJson()
            readList=message.reader.split(",") if message.reader else []
            json["isRead"]= "Y" if str(userid) in readList else "N"
            json['sender_desc']=message.getSenderDescAttr()
            resplist.append(json)
        return resplist

    def sendSystemMessage(sender, receiver, title,msg,toPage="")->ProjectMessage:
        message=ProjectMessage()
        message.sender=sender
        message.receiver=receiver
        message.title=title
        message.message=msg
        message.toPage=toPage
        message.projectId=-1
        message.save()
        return message